package com.glsc.ngateway.oaflow.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.base.domain.mysql.gateway.oaflow.TOaFlowMessageTable;
import com.glsc.ngateway.common.base.domain.mysql.gateway.oaflow.TOaFlowSystemTable;
import com.glsc.ngateway.oaflow.service.AppendixService;
import com.glsc.ngateway.oaflow.service.FlowService;
import com.glsc.ngateway.oaflow.service.MailService;
import com.glsc.ngateway.common.api.oaflow.resp.InterfaceResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 这个controller提供的两个接口供OA系统调用
 */
@RestController
public class OaCallController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AmqpTemplate rabbitTemplate;
    @Autowired
    FlowService flowService;
    @Autowired
    AppendixService appendixService;
    @Autowired
    MailService mailService;

    @RequestMapping(value = "oaDownloadAppendix/{appendixId}")
    public ResponseEntity<byte[]> oaDownloadAppendix(@PathVariable("appendixId") String appendixId, HttpServletRequest request) throws IOException {

        String targetName = appendixService.getAppendixPathById(appendixId);
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }


    /**
     * @param workflowId
     * @param requestId
     * @param workflowName
     * @param description
     * @return
     * @Description 接收OA数据
     */
    @RequestMapping(value = "forwardOARequest")
    public String forwardOARequest(@RequestParam("workflowId") String workflowId,
                                   @RequestParam("requestId") String requestId,
                                   @RequestParam("workflowName") String workflowName,
                                   @RequestParam(value = "description", defaultValue = "", required = false) String description) {
        String params = "workflowId:" + workflowId + ",requestId:" + requestId + ",workflowName:" + workflowName + ",description:" + description;
        //调用记录这里废弃，统一在接口处添加
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("workflowId", workflowId);
        messageMap.put("requestId", requestId);
        messageMap.put("workflowName", workflowName);
        messageMap.put("description", description);
        String message = JSONObject.toJSONString(messageMap);

        logger.info("流程请求信息放入前置队列:" + message);

        TOaFlowMessageTable oaFlowMessage = new TOaFlowMessageTable(workflowId, workflowName, requestId, description);
        List<TOaFlowSystemTable> recvSystem = flowService.getRecvSystem(workflowId);
        if (CollectionUtil.isEmpty(recvSystem)){
            Long currentWorkflowId = flowService.getCurrentWorkflowIdByWorkflowId(Long.valueOf(workflowId));
            mailService.sendMailToAdmin("发现新的workflowid无法找到对应消息队列",message);
        }
        for (TOaFlowSystemTable system : recvSystem) {
            this.rabbitTemplate.convertAndSend(system.getPreExchange(), system.getPreQueue(), message);
            //丢入前置队列后，60s后无消费会转入死信 x-dead-letter-exchange
        }

        Boolean result = flowService.insertOaMessage(oaFlowMessage);
        if (result) {
            logger.info("Success! OA流程消息写入数据库成功，参数为：" + params);
        } else {
            logger.error("Error! OA流程消息写入数据库失败，参数为：" + params);
        }
        return JSON.toJSONString(InterfaceResponse.returnSuccss("requestId为'" + requestId + "'的流程流转信息推送成功"));
    }


}
